package com.backend.demo1.config;

import com.backend.demo1.middlewares.JwtMiddleware;
import com.backend.demo1.middlewares.LoggingMiddleware;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.lang.NonNull; // 导入 Spring 的 NonNull 注解

@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    @Autowired
    private LoggingMiddleware loggingMiddleware;

    @Autowired
    private JwtMiddleware jwtMiddleware;


   @Override
    public void addInterceptors(@NonNull InterceptorRegistry registry) {
        registry.addInterceptor(jwtMiddleware)
                .addPathPatterns("/api/**"); // 所有 /api/** 的路由都会进入拦截器

        registry.addInterceptor(loggingMiddleware)
                .addPathPatterns("/**");
    }

    @Override
    public void addCorsMappings(@NonNull CorsRegistry registry) {
        registry.addMapping("/api/**") // 指定需要跨域的路径
                .allowedOrigins("http://localhost:8080") // 允许的来源
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法
                .allowedHeaders("Content-Type", "Authorization") // 允许的请求头
                .exposedHeaders("X-Custom-Header") // 暴露给客户端的响应头
                .maxAge(3600) // 预检请求的有效期（秒）
                .allowCredentials(true); // 是否允许发送Cookie
    }
}